import { udp } from "@cscec/udp-mobile-ui";

interface BaiduSpeechResponse {
  err_no: number;
  err_msg: string;
  result?: string[];
}

/**
 * 调用百度云短语音识别API
 * @param base64Audio 音频数据的Base64编码
 * @param len 音频文件长度而不是base64Audio的长度
 */
export const recognizeSpeech = async (
  fileString: string,
  len:number,
): Promise<string> => {
  const requestBody = {
    len: len,
    fileString:fileString,
  };

  try {
    const response:any = await udp.request.body({
        url: '/api/admin/getWord',
        headers: {
          'Content-Type': 'application/json',
        },
        data:requestBody
      });
    
    console.log(response)
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.msg}`);
    }

    const data: BaiduSpeechResponse = await response.data.json();
    console.log(data)
    if (data.err_no === 0 && data.result && data.result.length > 0) {
      return data.result[0];
    } else {
      throw new Error(`百度语音识别错误: ${data.err_msg} (错误码: ${data.err_no})`);
    }
  } catch (error) {
    console.error('语音识别API调用失败:', error);
    throw error;
  }
};

/**
 * 调用百度云短语音识别API
 * @param blob 音频文件
 */
export const recognizeSpeechByFile = async (
  blob:any,
): Promise<string> => {
    // 将Blob转换为File对象
  const file = new File([blob], 'recording.webm', { 
    type: blob.type || 'audio/webm' 
  });
  // 创建FormData并添加文件
  const formData = new FormData();
  formData.append('file', file);

   // 手动构建FormData并设置boundary
   // 注意：不要设置 Content-Type，让浏览器自动设置 multipart/form-data
 // const boundary = '----WebKitFormBoundary' + Math.random().toString(36);
    // 从 localStorage 获取登录信息
  const authToken = localStorage.getItem('__login__');
  // 构建请求头
  const headers = {};
  // 添加认证令牌
  if (authToken) {
    headers['user-token'] = authToken;
  }

  try {
    const options = {
    method: 'POST',
    headers: headers,
    body: formData
    };
    const response:any = await fetch('/api/admin/getWordByFile', options);

    console.log(response)
    // if (response.status!==200) {
    //   throw new Error(`HTTP error! status: ${response.msg}`);
    // }

    const data =  response.json();
    console.log(data)
    if (data) {
      return data;
    } else {
      throw new Error(`百度语音识别错误: ${data.err_msg} (错误码: ${data.err_no})`);
    }
  } catch (error) {
    console.error('语音识别API调用失败:', error);
    throw error;
  }
};